package org.jiuling.network.tools.request.http.impl;

import org.jiuling.local.tools.util.InputStreamUtil;
import org.jiuling.local.tools.verify.ObjectVerify;
import org.jiuling.network.tools.request.http.HttpRequest;
import org.jiuling.network.tools.request.http.base.HttpRequestBase;
import org.jiuling.network.tools.request.http.enums.RequestMethodEnum;
import org.jiuling.network.tools.request.http.model.HttpRequestResponse;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

/**
 * Http请求实现
 * @author 紫灵
 * @date 2024年02月20日 01时23分54秒
 */
public class HttpRequestImpl extends HttpRequestBase implements HttpRequest {

    public HttpRequestImpl(String path) {
        super(path);
    }

    @Override
    public HttpRequestResponse send() throws IOException {
        // 获取远程连接并强制转换为HTTP远程连接
        HttpURLConnection httpURLConnection = (HttpURLConnection)super.getURLConnection();
        RequestMethodEnum requestMethod = super.httpRequestDataConfig.getRequestMethod();
        // 设置请求方式
        if(!ObjectVerify.isNull(requestMethod)){
            httpURLConnection.setRequestMethod(requestMethod.getMethod());
        }
        // 开始链接
        super.connect(httpURLConnection);

        // 开始封装请求响应
        HttpRequestResponse httpRequestResponse = new HttpRequestResponse();
        httpRequestResponse.setHttpResponseStatus(httpURLConnection.getResponseCode());

        // 处理错误流信息
        try (InputStream errorInputStream = httpURLConnection.getErrorStream()){
            if(!ObjectVerify.isNull(errorInputStream)){
                httpRequestResponse.setErrorBody(InputStreamUtil.readInputStream(errorInputStream));
            }
        }catch (FileNotFoundException ignored){
            // 该异常不处理
        }

        // 处理数据流信息
        try (InputStream inputStream = httpURLConnection.getInputStream()){
            if(!ObjectVerify.isNull(inputStream)){
                httpRequestResponse.setBody(InputStreamUtil.readInputStream(inputStream));
            }
        }catch (FileNotFoundException ignored){
            // 该异常不处理
        }
        // 断开链接
        httpURLConnection.disconnect();
        return httpRequestResponse;
    }


}
